<?php
namespace lightblog\engine;

class view {
    function __construct($module, $controller, $action) {
        $this->module = $module;
        $this->controller = $controller;
        $this->action = $action;
    }

    function display($data = array()) {
        $view_path = \lightblog::$app->config['view']['path'];
        $template = "{$this->module}/{$view_path}/{$this->controller}/{$this->action}.php";

        $this->template = $template;

        try {
            if (!file_exists($template))
                throw new \Exception("模板文件($template)不存在");
        } catch (\Exception $e) {
            exception_error($e);
        }

        return $this->mkOutput($template, $data);
    }

    function displayFile($filename, $data = array()) {
        $view_path = \lightblog::$app->config['view']['path'];
        $template = "{$this->module}/{$view_path}/{$filename}.php";
        $this->template = $template;

        try {
            if (!file_exists($template))
                throw new \Exception("模板文件($template)不存在");
        } catch (\Exception $e) {
            exception_error($e);
        }

        return $this->mkOutput($template, $data);
    }

    private function mkOutput($filepath, $data) {
        ob_start();
        ob_implicit_flush(false);
        extract($data, EXTR_OVERWRITE);
        require($filepath);

        return ob_get_clean();
    }
}
